import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/models/home/city_model.dart';
import 'package:share_fit/app/routes/home_routes.dart';

import 'state.dart';

class WeatherLocationSwitchLogic extends BaseController {
  final WeatherLocationSwitchState state = WeatherLocationSwitchState();

  loadCityData() {
    rootBundle.loadString('assets/json/cities.json').then((cityJson) => _initCityList(cityJson));
  }

  _initCityList(String cityJson) {
    List cityList = jsonDecode(cityJson);
    for (var cityMap in cityList) {
      state.cityList.add(CityModel(
        cityMap['id'],
        name: cityMap['name'],
        lat: cityMap['lat'],
        lon: cityMap['lon'],
        adm2: cityMap['adm2'],
        adm1: cityMap['adm1'],
        country: cityMap['country'],
      ));
    }

    update(['city_list']);
  }

  void changeIndex(index) {
    state.currentIndex = index;
    update();
  }

  filterRegion(String value) {
    state.cityList.clear();
    loadCityData();

    if (value.isNotEmpty) {
      Iterable<CityModel> iterable = state.cityList.where((element) => element.name!.contains(value));
      state.cityList.clear();
      state.cityList.addAll(iterable);
      update(['city_list']);
    }
  }

  @override
  String getRemotePath() {
    return '';
  }

  @override
  void initState() {
    loadCityData();
  }

  @override
  void onRemoteEvent(event, method) {
    // TODO: implement onRemoteEvent
  }

  onCitySelected(CityModel city) {
    Get.offNamed(HomeRoutes.weatherPage, arguments: city);
  }
}
